# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Live value resolution.

Live values are extracted from the known execution context.

Requires annotations generated by AccessResolver.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gast

from tensorflow.contrib.py2tf.pyct import anno


class LiveValueResolver(gast.NodeTransformer):
  """Annotates nodes with live values."""

  def __init__(self, namespace, literals):
    """Create a new resolver.

    Args:
      namespace: A dict representing the namespace visible to the AST in the
          intended execution context.
      literals: A dict mapping literal lymbol names to their value. An example
          literal is "None".
    """
    self.namespace = namespace
    self.literals = literals

  def visit_Name(self, node):
    self.generic_visit(node)
    if isinstance(node.ctx, gast.Load):
      assert anno.hasanno(node, 'is_local'), node
      symbol_is_local = anno.getanno(node, 'is_local')
      if not symbol_is_local:
        if node.id in self.literals:
          anno.setanno(node, 'live_val', self.literals[node.id])
          # TODO(mdan): Could live values have FQNs? i.e. 'a'.join()
        elif node.id in self.namespace:
          obj = self.namespace[node.id]
          anno.setanno(node, 'live_val', obj)
          anno.setanno(node, 'fqn', (obj.__name__,))
        else:
          raise ValueError('Could not find global symbol %s.' % node.id)
      else:
        pass
        # TODO(mdan): Attempt to trace its value through the local chain.
        # TODO(mdan): Use type annotations as fallback.
    return node

  def visit_Attribute(self, node):
    self.generic_visit(node)
    if anno.hasanno(node.value, 'live_val'):
      assert anno.hasanno(node.value, 'fqn')
      parent_object = anno.getanno(node.value, 'live_val')
      if not hasattr(parent_object, node.attr):
        raise AttributeError('%s has no attribute %s' % (parent_object,
                                                         node.attr))
      anno.setanno(node, 'live_val', getattr(parent_object, node.attr))
      anno.setanno(node, 'fqn', anno.getanno(node.value, 'fqn') + (node.attr,))
    # TODO(mdan): Figure out what to do when calling attribute on local object.
    # Maybe just leave as-is?
    return node


def resolve(node, namespace, literals):
  return LiveValueResolver(namespace, literals).visit(node)
